package com.example.demo.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    // token available time
    public static final int JWT_TTL_DAY = 7;  // 7 day
    public static final String DEFAULT_KEY = "key";  // 7 day
    // set key
    public static final byte[] JWT_KEY = "CONFERENCE_RESERVATION_KEY99988898989898".getBytes();

    /**
     * generator token string
     */
    public static String createToken(Map<String, Object> payloads) {
        Instant expires = LocalDateTime.now().plusDays(JWT_TTL_DAY).toInstant(ZoneOffset.of("+8"));
        JWT jwt = JWT.create();
        for (String key : payloads.keySet()) {
            jwt.setPayload(key, payloads.get(key));
        }

        jwt.setKey(JWT_KEY);
        jwt.setExpiresAt(Date.from(expires));

        return jwt.sign();
    }

    /**
     * generator token string (only one key value)
     */
    public static String createToken(String key, String value) {
        HashMap<String, Object> data = new HashMap<>();
        data.put(key, value);
        return createToken(data);
    }

    /**
     * create token  by default key
     */
    public static String createToken(String value) {
        HashMap<String, Object> data = new HashMap<>();
        data.put(DEFAULT_KEY, value);
        return createToken(data);
    }

    /**
     * check token available
     */
    public static boolean isAvailable(String token) {
        if (StrUtil.isBlank(token)){
            return false;
        }
        return JWT.of(token).setKey(JWT_KEY).validate(0);
    }

    /**
     * get token content
     */
    public static Object getPayload(String token, String key) {
        if (isAvailable(token)) {
            return JWT.of(token).setKey(JWT_KEY).getPayloads().get(key);
        } else {
            return null;
        }
    }
    /**
     * get token content by default key
     */
    public static Object getPayload(String token) {
        if (isAvailable(token)) {
            return JWT.of(token).setKey(JWT_KEY).getPayloads().get(DEFAULT_KEY);
        } else {
            return null;
        }
    }


}